package com.sa.web.util.tags;

import java.io.IOException;
import java.io.Writer;

import org.apache.struts2.components.Component;

import com.opensymphony.xwork2.util.ValueStack;
import com.sa.web.bean.PageBean;

public class PageService extends Component {
	
	private ValueStack valueStack;
	
	private String action;
	
	private int pageCount;

	public PageService(ValueStack stack) {
		super(stack);
		valueStack = stack;
	}
	
	
	@Override
	public boolean start(Writer writer) {
		try {
			PageBean pb = (PageBean) valueStack.findValue("pb");
			int totlePage = (pb.getTotleCount() - 1) / pageCount + 1;
			int currentPage = pb.getCurrentPage();
			StringBuilder styleClass = new StringBuilder("style='padding:10px 10px;");
			String cursorStyle = "cursor:pointer;'";
			String underLineStyle = "text-decoration: none";
			String paramHtml_1 = "?pb.currentPage=";
			String paramHtml_2 = "&pb.totleCount=";
			StringBuilder hrefHtml = new StringBuilder("<a href='");
			StringBuilder firstHtml = new StringBuilder(hrefHtml).append(action).append(paramHtml_1).append(1).append(paramHtml_2).append(pb.getTotleCount()).append("'").append(styleClass).append(cursorStyle).append(">首页</a>|");
			StringBuilder lastHtml = new StringBuilder(hrefHtml).append(action).append(paramHtml_1).append(totlePage).append(paramHtml_2).append(pb.getTotleCount()).append("'").append(styleClass).append(cursorStyle).append(">末页</a>");
			StringBuilder upHtml = new StringBuilder(90);
			StringBuilder downHtml = new StringBuilder(90);
			StringBuilder pageHtml = new StringBuilder(400);
			if(-- currentPage < 1){
				upHtml.append("<a ").append(styleClass).append(underLineStyle).append("'>上一页</a>|");
			}else{
				upHtml.append("<a ").append(hrefHtml).append(action).append(paramHtml_1).append(currentPage).append(paramHtml_2).append(pb.getTotleCount()).append("'").append(styleClass).append("'>上一页</a>|");
			}
			
			if( (currentPage + 2) > totlePage){
				downHtml.append("<a ").append(styleClass).append(underLineStyle).append("'>下一页</a>|");
			}else{
				downHtml.append("<a href='").append(action).append(paramHtml_1).append(currentPage + 2).append(paramHtml_2).append(pb.getTotleCount()).append("'").append(styleClass).append("'>下一页</a>|");
			}
			pageHtml.append(firstHtml).append(upHtml).append(downHtml).append(lastHtml);
			writer.write(pageHtml.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.start(writer);
	}


	public ValueStack getValueStack() {
		return valueStack;
	}


	public void setValueStack(ValueStack valueStack) {
		this.valueStack = valueStack;
	}


	public String getAction() {
		return action;
	}


	public void setAction(String action) {
		this.action = action;
	}


	public int getPageCount() {
		return pageCount;
	}


	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}
	
}
